﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Windows.Forms;
using Lyon.Utility;

namespace Lyon.WinForm
{
    internal partial class WaitPanel : UserControl
    {
        AsyncThread async = new AsyncThread();

        Callback action;
        Callback finished;
        Callback abort;

        public WaitPanel(Callback action, Callback finished, Callback abort)
        {
            this.action = action;
            this.finished = finished;
            this.abort = abort;

            InitializeComponent();

            this.Disposed += new EventHandler(WaitPanel_Disposed);
        }

        public string Context
        {
            get
            {
                return labelControl1.Text;
            }
            set
            {
                labelControl1.Text = value;
            }
        }

        public void ShowDialog(Control control)
        {
            control.Controls.Add(this);
            this.Dock = DockStyle.Fill;
            this.BringToFront();
        }

        public void DoAction()
        {
            async.Start(delegate
            {
                try
                {
                    action();
                }
                catch (System.Threading.ThreadAbortException)
                {
                    async.Callback(delegate
                    {
                        RunAbort();
                    });
                    return;
                }
                catch (Exception ex)
                {
                    async.Callback(delegate
                    {
                        string message = "执行过程中出现错误.";
                        ExceptionMessageBox.Show(this, ex, message, this.Text, MessageBoxButtons.OK, MessageBoxIcon.Error);
                        
                        RunAbort();
                    });
                    return;
                }
                async.Callback(delegate
                {
                    RunFinished();
                });
            });
        }
        private void RunFinished()
        {
            this.Dispose();
            if (finished != null)
                try { finished(); }
                catch { }
        }
        private void RunAbort()
        {
            this.Dispose();
            if (abort != null)
                try { abort(); }
                catch { }
        }

        

        private void BT_Cancel_Click(object sender, EventArgs e)
        {
            this.Dispose();
        }

        private void WaitPanel_Disposed(object sender, EventArgs e)
        {
            if (BT_Cancel.Enabled)
            {
                BT_Cancel.Enabled = false;
                BT_Cancel.Text = "取消中……";
                if (async.IsStart)
                    async.Stop();
            }
        }
    }
}
